<script setup lang="ts">
import { editUserInfo, getUserInfoById } from '@/api/user';
import { UserInfo } from '@/api/user/type';
import { onMounted, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast, showSuccessToast } from 'vant';
import Avatar from '../components/Avatar.vue';

// 扩展UserInfo类型，添加索引签名支持动态字段访问
interface ExtendedUserInfo extends UserInfo {
  [key: string]: any; // 添加索引签名
}

const route = useRoute();
const router = useRouter();
const userInfo = ref({} as ExtendedUserInfo);
const loading = ref(true);
const submitting = ref(false);
const editField = computed(() => route.query.field as string || 'nickname');

const fieldLabels: Record<string, string> = {
  nickname: '昵称',
  signature: '个性签名',
  sex: '性别',
  phone: '手机号',
  email: '电子邮箱',
  school: '学校',
  major: '专业',
  avatar: '头像'
};

const genderOptions = [
  { text: '男', value: '男' },
  { text: '女', value: '女' },
  { text: '保密', value: '保密' }
];

onMounted(async () => {
  const userId = route.query.userId as string;
  if (userId) {
    try {
      loading.value = true;
      const res = await getUserInfoById(userId);
      userInfo.value = res.data as ExtendedUserInfo;
    } catch (error) {
      console.error('获取用户信息失败', error);
      showToast('获取用户信息失败');
    } finally {
      loading.value = false;
    }
  } else {
    loading.value = false;
    showToast('用户ID不存在');
    router.back();
  }
});

const submit = async () => {
  try {
    submitting.value = true;
    await editUserInfo(userInfo.value);
    showSuccessToast(`${fieldLabels[editField.value] || '信息'}修改成功`);
    setTimeout(() => {
      router.back();
    }, 1000);
  } catch (error) {
    console.error('修改用户信息失败', error);
    showToast('修改失败，请稍后再试');
  } finally {
    submitting.value = false;
  }
};

const cancel = () => {
  router.back();
};
</script>

<template>
  <div class="edit-profile-container">
    <div class="content-card">
      <div class="card-header">
        <h2>编辑{{ fieldLabels[editField] || '个人信息' }}</h2>
      </div>
      
      <van-loading v-if="loading" class="loading" type="spinner" color="#1989fa" />
      
      <div v-else class="form-container">
        <!-- 头像编辑 -->
        <div v-if="editField === 'avatar'" class="avatar-edit">
          <Avatar v-model="userInfo.avatar" />
        </div>
        
        <!-- 性别选择 -->
        <template v-else-if="editField === 'sex'">
          <van-radio-group v-model="userInfo.sex" direction="horizontal" class="gender-group">
            <van-radio 
              v-for="option in genderOptions" 
              :key="option.value"
              :name="option.value"
              icon-size="24px"
              checked-color="#1989fa"
            >
              {{ option.text }}
            </van-radio>
          </van-radio-group>
        </template>
        
        <!-- 常规表单字段 -->
        <template v-else>
          <van-field
            v-model="userInfo[editField]"
            :label="fieldLabels[editField] || '信息'"
            :placeholder="`请输入${fieldLabels[editField] || '信息'}`"
            :type="editField === 'phone' ? 'tel' : editField === 'email' ? 'email' : 'text'"
            :rows="editField === 'signature' ? 4 : 1"
            :autosize="editField === 'signature'"
            :maxlength="editField === 'signature' ? 200 : 50"
            :show-word-limit="editField === 'signature'"
            :input-align="editField === 'signature' ? 'left' : 'right'"
            :required="['nickname', 'phone'].includes(editField)"
          />
          
          <div v-if="editField === 'signature'" class="field-tip">
            个性签名是展示在个人资料中的一段话，可以写下您的座右铭或自我介绍。
          </div>
        </template>
        
        <div class="btn-group">
          <van-button plain size="normal" @click="cancel">取消</van-button>
          <van-button 
            type="primary" 
            size="normal" 
            @click="submit"
            :loading="submitting"
            :disabled="loading || submitting"
          >
            保存
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.edit-profile-container {
  max-width: 100%;
  padding: 16px;
  
  .content-card {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    padding: 24px;
    margin-bottom: 24px;
    transition: all 0.3s ease;
    
    .card-header {
      margin-bottom: 24px;
      border-bottom: 1px solid #f2f3f5;
      padding-bottom: 16px;
      
      h2 {
        font-size: 20px;
        font-weight: 600;
        color: #323233;
        margin: 0;
      }
    }
    
    .loading {
      display: flex;
      justify-content: center;
      padding: 40px 0;
    }
    
    .form-container {
      .field-tip {
        margin-top: 8px;
        color: #999;
        font-size: 12px;
        line-height: 1.5;
        padding: 0 16px;
      }
      
      .gender-group {
        display: flex;
        justify-content: flex-start;
        gap: 24px;
        padding: 16px;
      }
      
      .avatar-edit {
        display: flex;
        justify-content: center;
        padding: 24px 0;
      }
      
      .btn-group {
        display: flex;
        justify-content: flex-end;
        margin-top: 32px;
        gap: 12px;
      }
    }
  }
}
</style>